package com.jzo2o.orders.manager.strategy;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.jzo2o.api.market.CouponApi;
import com.jzo2o.api.market.dto.request.CouponUseBackReqDTO;
import com.jzo2o.common.utils.ObjectUtils;
import com.jzo2o.orders.base.enums.OrderStatusEnum;
import com.jzo2o.orders.base.mapper.OrdersCanceledMapper;
import com.jzo2o.orders.base.mapper.OrdersMapper;
import com.jzo2o.orders.base.model.domain.Orders;
import com.jzo2o.orders.manager.model.dto.OrderCancelDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

//订单取消策略管理类
@Component
@Slf4j
public class OrderCancelStrategyManager {
    Map<String, OrderCancelStrategy> strategyMap =new HashMap<>();

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private CouponApi couponApi;
    @PostConstruct//在当前类初始化之后执行
    public void init() {
        //key ：用户类型+订单状态
        //value：策略对象

        strategyMap= SpringUtil.getBeansOfType(OrderCancelStrategy.class);
        log.info("策略管理器初始化完成");
    }

    public void cancel(OrderCancelDTO orderCancelDTO) {
        //1.获取订单信息并判断当前订单是否存在
        Orders orders = ordersMapper.selectById(orderCancelDTO.getId());
        if (ObjectUtils.isNull(orders))
        {
            throw new RuntimeException("订单不存在");
        }

        BeanUtil.copyProperties(orders, orderCancelDTO);

        //添加退回优惠券的逻辑
        if (orders.getDiscountAmount().compareTo(BigDecimal.ZERO) > 0){
            CouponUseBackReqDTO couponUseBackReqDTO = new CouponUseBackReqDTO();
            couponUseBackReqDTO.setOrdersId(orders.getId());//订单id
            couponUseBackReqDTO.setUserId(orders.getUserId());//用户id
            couponApi.useBack(couponUseBackReqDTO);
        }


        //2.根据当前订单的用户类型和订单状态获取对应的订单取消策略   订单取消策略的key:
        String key = orderCancelDTO.getCurrentUserType() + ":" + OrderStatusEnum.codeOf(orders.getOrdersStatus()).toString();
        OrderCancelStrategy strategy = strategyMap.get(key);
        if(ObjectUtils.isNull(strategy))
        {
            throw new RuntimeException("订单取消策略不存在");
        }

        strategy.cancel(orderCancelDTO);
    }
}
